package com.qd.system.service.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.util.page.BaseQuery;
import com.cdqidi.util.sql.SqlParam;
import com.qd.common.sys.domain.login.UserOperator;
import com.qd.common.sys.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户操作
 *
 * @author sjk
 */
@Slf4j
public class UserOperatorService {
    private UserOperatorService() {

    }

    public static final String DB_ORG_PARENT_ID = "parent_id";
    public static final String DB_ORG_ID = "id";

    public static final String ORG = "org";
    public static final String ORG_ID = "orgId";
    public static final String ORG_IDS = "orgIds";
    public static final String PERSON_ID = "personId";
    /**
     * 直接存储可以使用的sql，类似于cl.parent_id in (select id from sys_org_cl where parent_id='')
     */
    public static final String DATA_SCOPE = "dataScope";
    /**
     * 存储字段cl.person_id
     */
    public static final String DATA_SCOPE_IN_SQL_COLUMN = "dataScopeInSqlColumn";
    /**
     * 存储值select id from sys_org_cl where parent_id=''
     */
    public static final String DATA_SCOPE_IN_SQL_VALUE = "dataScopeInSqlValue";
    public static final String FUN_SQL = "funSql";

    public static String buildDeptSql(String dataScope, String currentDeptId) {
        final StringBuilder stringBuilder = new StringBuilder("select id from sys_org_cl where");
        if (dataScope.equals(ORG_IDS)) {
            stringBuilder.append(" parent_id='");
        } else {
            stringBuilder.append(" id='");
        }
        stringBuilder.append(currentDeptId);
        stringBuilder.append("'");
        return stringBuilder.toString();
    }

    /**
     * 转换成sql语句
     *
     * @return sql语句
     */
    public static String sqlParamToString(List<SqlParam> sqlParamList) {
        final StringBuilder str = new StringBuilder();
        if (null != sqlParamList && !sqlParamList.isEmpty()) {
            SqlParam sqlParam;
            for (int i = 0; i < sqlParamList.size(); i++) {
                sqlParam = sqlParamList.get(i);
                str.append(buildColumnName(sqlParam));
                if (sqlParam.getOperator().equals(SqlParam.SQL_IN)) {
                    str.append(" ");
                }
                str.append(sqlParam.getOperator());
                str.append(sqlParam.getValue());
                if (i < sqlParamList.size() - 1) {
                    str.append(" and ");
                }
            }
        }
        return str.toString();
    }

    /**
     * 拼装名字，cl.org_id
     *
     * @param sqlParam 参数
     */
    public static StringBuilder buildColumnName(SqlParam sqlParam) {
        StringBuilder str = new StringBuilder();
        if (StringUtils.hasLength(sqlParam.getAlias())) {
            str.append(sqlParam.getAlias());
            str.append(".");
        }
        str.append(sqlParam.getColumn());
        return str;
    }

    public static <T> void buildQuery(BaseQuery baseQuery, QueryWrapper<T> queryWrapper) {
        final UserOperator userOperator = SecurityUtils.getLoginUser().getUserOperator();
        if (null == userOperator) {
            return;
        }
        Map<String, Object> sysParams = baseQuery.getSysParams();
        if (null == sysParams || sysParams.isEmpty()) {
            sysParams = new HashMap<>(10);
        }
        final List<SqlParam> listSqlParams = userOperator.getListSqlParams();
        if (null != listSqlParams && !listSqlParams.isEmpty()) {
            final String sql = sqlParamToString(listSqlParams);
            queryWrapper.apply(sql);
            sysParams.put(FUN_SQL, sql);
        }
        final Map<String, Object> params = userOperator.getParams();
        if (null != params && !params.isEmpty()) {
            sysParams.putAll(params);
        }
        final String val = sysParams.get(UserOperatorService.DATA_SCOPE).toString();
        if (StringUtils.hasLength(val)) {
            queryWrapper.apply(val);
        }
        baseQuery.setSysParams(sysParams);
    }

    public static void buildOrgIds(BaseQuery baseQuery, QueryWrapper<?> queryWrapper) {
        buildOrgIds(baseQuery, queryWrapper, "");
    }

    public static void buildOrgIds(BaseQuery baseQuery, QueryWrapper<?> queryWrapper, String tableAlias) {
        if (null == baseQuery) {
            return;
        }
        final String[] orgIds = baseQuery.getOrgIds();
        if (null == orgIds) {
            return;
        }
        if (orgIds.length == 2) {
            queryWrapper.eq(tableAlias + orgIds[0], orgIds[1]);
        }
    }

    /**
     * 拼装in的sql
     * queryWrapper.inSql("cl.id","select id from sys_org_cl where parent_id=1");
     *
     * @param baseQuery    系统参数
     * @param queryWrapper 查询
     */
    public static void buildInSql(BaseQuery baseQuery, QueryWrapper<?> queryWrapper) {
        final Map<String, Object> sysParams = baseQuery.getSysParams();
        if (null == sysParams || sysParams.isEmpty()) {
            return;
        }
        final Object column = sysParams.get(UserOperatorService.DATA_SCOPE_IN_SQL_COLUMN);
        final Object value = sysParams.get(UserOperatorService.DATA_SCOPE_IN_SQL_VALUE);
        if (null == column || null == value) {
            return;
        }
        queryWrapper.inSql(column.toString(), value.toString());
    }
}